<template>
  <div class="supply-purchase-manage">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">物资采购</h2>
      <div class="local-preview">本地预览</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>货物名称</label>
          <input 
            v-model="searchForm.goodsName" 
            type="text" 
            placeholder="请输入货物名称" 
            class="form-input" 
          />
        </div>
        <div class="form-item">
          <label>材质</label>
          <select v-model="searchForm.materialid" class="form-select">
            <option value="">全部</option>
            <option v-for="material in materialList" :key="material.id" :value="material.id">
              {{ material.materialName }}
            </option>
          </select>
        </div>
        <div class="form-item">
          <label>产地</label>
          <input 
            v-model="searchForm.origin" 
            type="text" 
            placeholder="请输入产地" 
            class="form-input" 
          />
        </div>
        <div class="form-item">
          <label>审批人姓名</label>
          <input 
            v-model="searchForm.approvalByName" 
            type="text" 
            placeholder="请输入审批人姓名" 
            class="form-input" 
          />
        </div>
        <div class="form-item">
          <label>审批状态</label>
          <select v-model="searchForm.approvalStatus" class="form-select">
            <option value="">全部</option>
            <option value="0">待审批</option>
            <option value="1">已通过</option>
            <option value="2">已拒绝</option>
          </select>
        </div>
        <div class="form-actions">
          <button @click="handleSearch" class="btn btn-primary">
            <i class="search-icon"></i>查询
          </button>
          <button @click="handleReset" class="btn btn-secondary">
            <i class="refresh-icon"></i>重置
          </button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <button @click="handleAdd" class="btn btn-primary">新增</button>
      <button @click="handleBatchDelete" class="btn btn-danger">批量删除</button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <table class="data-table">
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="handleSelectAll" class="checkbox" /></th>
            <th>货物名称</th>
            <th>类型</th>
            <th>材质</th>
            <th>规格</th>
            <th>产地</th>
            <th>数量</th>
            <th>用途描述</th>
            <th>预期交付日期</th>
            <th>备注</th>
            <th>创建时间</th>
            <th>审批状态</th>
            <th>审批人</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="14" class="loading-cell">
              <div class="loading-spinner">加载中...</div>
            </td>
          </tr>
          <tr v-else-if="tableData.length === 0">
            <td colspan="14" class="empty-cell">
              暂无数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in tableData" :key="item.id">
            <td><input type="checkbox" v-model="item.selected" @change="handleRowSelect" class="checkbox" /></td>
            <td>{{ item.goodsName || "-" }}</td>
            <td>{{ item.typeName || "-" }}</td>
            <td>{{ item.materialName || "-" }}</td>
            <td>{{ item.size || "-" }}</td>
            <td>{{ item.origin || "-" }}</td>
            <td>{{ item.quantity || 0 }}</td>
            <td>{{ item.usageDescription || "-" }}</td>
            <td>{{ formatDate(item.expectedDeliveryDate) }}</td>
            <td>{{ item.note || "-" }}</td>
            <td>{{ formatDate(item.createdTime) }}</td>
            <td>
              <span :class="['status-badge', getStatusClass(item.approvalStatus)]">
                {{ getStatusText(item.approvalStatus) }}
              </span>
            </td>
            <td>{{ item.approvalByName || "-" }}</td>
            <td>
              <div class="action-links">
                <a @click="handleView(item)" class="action-link link-view">查看</a>
                <a @click="handleEdit(item)" class="action-link link-edit">编辑</a>
                <a @click="handleSubmitApproval(item)" class="action-link link-submit" v-if="item.approvalStatus === 0">提交审批</a>
                <a @click="handleDelete(item)" class="action-link link-delete">删除</a>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">共{{ totalPages }}页/{{ totalCount }}条数据</div>
      <div class="pagination-controls">
        <button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1" class="btn-pagination">&lt;</button>
        <button 
          v-for="page in visiblePages" 
          :key="page" 
          @click="goToPage(page)" 
          :class="['btn-pagination', { active: page === currentPage }]"
        >
          {{ page }}
        </button>
        <button v-if="showEllipsis" class="btn-pagination disabled">...</button>
        <button 
          v-if="showLastPage" 
          @click="goToPage(totalPages)" 
          :class="['btn-pagination', { active: currentPage === totalPages }]"
        >
          {{ totalPages }}
        </button>
        <button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages" class="btn-pagination">&gt;</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input 
          v-model="jumpToPage" 
          type="number" 
          min="1" 
          :max="totalPages" 
          @keyup.enter="jumpToSpecificPage" 
          class="jump-input" 
        />
        <span>页</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { materialApi } from '@/api'

// 路由
const router = useRouter()

// 响应式数据
const searchForm = reactive({
  goodsName: '',
  materialid: '',
  origin: '',
  approvalByName: '',
  approvalStatus: ''
})

const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const totalCount = ref(0)
const jumpToPage = ref(1)
const loading = ref(false)

// 表格数据
const tableData = ref([])

// 材质列表
const materialList = ref([])

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const showEllipsis = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

const showLastPage = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

// 获取材质列表
const fetchMaterialList = async () => {
  try {
    const response = await materialApi.getMaterials()

    if (response.code === 200) {
      materialList.value = response.data
    } else {
      throw new Error(response.message || '获取材质列表失败')
    }
  } catch (error) {
    console.error('获取材质列表出错:', error)
    // 如果API调用失败，使用模拟数据
    materialList.value = [
      { id: 1, materialName: "金属" },
      { id: 2, materialName: "橡胶" },
      { id: 3, materialName: "塑料" },
      { id: 4, materialName: "液体" },
      { id: 5, materialName: "纸质" }
    ]
    console.log('使用模拟材质数据')
  }
}

// 获取物资采购数据
const fetchSupplyPurchaseData = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      ...(searchForm.goodsName && { goodsName: searchForm.goodsName }),
      ...(searchForm.materialid && { materialid: parseInt(searchForm.materialid) }),
      ...(searchForm.origin && { origin: searchForm.origin }),
      ...(searchForm.approvalByName && { approvalByName: searchForm.approvalByName }),
      ...(searchForm.approvalStatus && { approvalStatus: parseInt(searchForm.approvalStatus) })
    }

    // 调用封装的API方法
    const response = await materialApi.getSupplyPurchaseList(params)

    if (response.code === 200) {
      const { data } = response.data
      console.log('API响应数据结构:', data)
      
      // 安全检查数据结构
      if (data && Array.isArray(data.data)) {
        tableData.value = data.data.map(item => ({
          ...item,
          selected: false
        }))
        totalCount.value = data.totalCount || 0
        totalPages.value = data.totalPage || 0
      } else if (Array.isArray(data)) {
        // 如果data直接是数组
        tableData.value = data.map(item => ({
          ...item,
          selected: false
        }))
        totalCount.value = data.length
        totalPages.value = Math.ceil(data.length / pageSize.value)
      } else {
        console.warn('意外的数据结构:', data)
        tableData.value = []
        totalCount.value = 0
        totalPages.value = 0
      }
    } else {
      throw new Error(response.message || '获取数据失败')
    }
    
  } catch (error) {
    console.error('获取数据出错:', error)
    // 如果API调用失败，使用模拟数据
    const mockData = [
      {
        id: 1,
        goodsName: "轮胎",
        typeId: 1,
        materialid: 2,
        size: "1200R20",
        origin: "中国-上海",
        quantity: 10,
        expectedDeliveryDate: "2025-09-28T06:39:01.56",
        usageDescription: "车库备胎数量不够",
        note: "-",
        createdTime: "2025-09-28T06:39:01.56",
        processDetailCode: "SP001",
        approvalStatus: 0,
        approvalByName: "王大宝",
        typeName: "车辆用品",
        materialName: "橡胶",
        selected: false
      }
    ]
    
    tableData.value = mockData
    totalCount.value = 1
    totalPages.value = 1
    
    alert('获取数据出错，已显示模拟数据')
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  fetchSupplyPurchaseData()
}

const handleReset = () => {
  searchForm.goodsName = ''
  searchForm.materialid = ''
  searchForm.origin = ''
  searchForm.approvalByName = ''
  searchForm.approvalStatus = ''
  currentPage.value = 1
  fetchSupplyPurchaseData()
}

const handleAdd = () => {
  console.log('新增')
  // 跳转到新增页面
  router.push('/AddSupplyPurchaseManage')
}

const handleBatchDelete = async () => {
  const selectedItems = tableData.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    alert('请选择要删除的项目')
    return
  }
  
  if (confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
    try {
      // 提取选中的ID数组
      const ids = selectedItems.map(item => item.id)
      
      // 调用封装的API方法批量删除
      const response = await materialApi.deleteListSupplyPurchase(ids)

      if (response.code === 200) {
        alert(`批量删除成功，共删除 ${selectedItems.length} 条记录`)
        // 刷新数据
        fetchSupplyPurchaseData()
      } else {
        throw new Error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除出错:', error)
      alert('批量删除失败，请重试')
    }
  }
}

const handleSelectAll = () => {
  tableData.value.forEach(item => {
    item.selected = selectAll.value
  })
}

const handleRowSelect = () => {
  const selectedCount = tableData.value.filter(item => item.selected).length
  selectAll.value = selectedCount === tableData.value.length
}

const handleDelete = async (item) => {
  console.log('删除:', item)
  if (confirm(`确定要删除 "${item.goodsName}" 吗？`)) {
    try {
      // 调用封装的API方法删除
      const response = await materialApi.deleteSupplyPurchase(item.id)

      if (response.code === 200) {
        alert('删除成功')
        // 刷新数据
        fetchSupplyPurchaseData()
      } else {
        throw new Error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除出错:', error)
      alert('删除失败，请重试')
    }
  }
}

const handleView = (item) => {
  console.log('查看:', item)
  // 跳转到物资采购查看页面，传递ID参数
  router.push({
    path: '/AddSupplyPurchaseManage',
    query: { id: item.id, mode: 'view' }
  })
}

const handleEdit = (item) => {
  console.log('编辑:', item)
  // 跳转到物资采购编辑页面，传递ID参数
  router.push({
    path: '/AddSupplyPurchaseManage',
    query: { id: item.id, mode: 'edit' }
  })
}

const handleSubmitApproval = (item) => {
  console.log('提交审批:', item)
  if (confirm(`确定要提交 "${item.goodsName}" 进行审批吗？`)) {
    // 这里添加提交审批逻辑
    try {
      // 调用提交审批API
      const requestData = {
        id: item.id,
        approvalStatus: 0, // 待审批状态
        submittedTime: new Date().toISOString(),
        submittedByName: '当前用户' // 这里应该从用户信息中获取
      }
      
      console.log('提交审批数据:', requestData)
      
      // 这里可以调用实际的API
      // const response = await axios.post('/api/SupplyPurchase/SubmitApproval', requestData)
      
      alert('提交审批成功')
      // 刷新数据
      fetchSupplyPurchaseData()
    } catch (error) {
      console.error('提交审批失败:', error)
      alert('提交审批失败，请重试')
    }
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpToPage.value = page
    fetchSupplyPurchaseData()
  }
}

const jumpToSpecificPage = () => {
  goToPage(jumpToPage.value)
}

const getStatusClass = (status) => {
  const statusMap = {
    0: 'status-waiting',
    1: 'status-approved',
    2: 'status-rejected'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审批',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchMaterialList()
  fetchSupplyPurchaseData()
})
</script>

<style scoped>
.supply-purchase-manage {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.local-preview {
  background: #e8f4fd;
  color: #1890ff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

/* 搜索筛选区域 */
.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  align-items: end;
}

.form-item {
  display: flex;
  flex-direction: column;
}

.form-item label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-actions {
  display: flex;
  gap: 12px;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover {
  background: #40a9ff;
}

.btn-secondary {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.btn-secondary:hover {
  background: #e6f7ff;
  color: #1890ff;
  border-color: #1890ff;
}

.btn-danger {
  background: #ff4d4f;
  color: white;
}

.btn-danger:hover {
  background: #ff7875;
}

.search-icon::before {
  content: "🔍";
  font-size: 12px;
}

.refresh-icon::before {
  content: "🔄";
  font-size: 12px;
}

/* 操作按钮区域 */
.action-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

/* 数据表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.data-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table tbody tr:hover {
  background: #f5f5f5;
}

.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 加载状态样式 */
.loading-cell, .empty-cell {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 状态标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-waiting {
  background: #fff7e6;
  color: #fa8c16;
}

.status-approved {
  background: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background: #fff2f0;
  color: #ff4d4f;
}

/* 操作链接样式 */
.action-links {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.action-link {
  color: #1890ff;
  text-decoration: none;
  font-size: 12px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 2px;
  transition: all 0.3s;
  white-space: nowrap;
}

.action-link:hover {
  background: #e6f7ff;
  text-decoration: underline;
}

.link-view {
  color: #1890ff;
}

.link-view:hover {
  background: #e6f7ff;
  color: #40a9ff;
}

.link-edit {
  color: #52c41a;
}

.link-edit:hover {
  background: #f6ffed;
  color: #73d13d;
}

.link-submit {
  color: #722ed1;
}

.link-submit:hover {
  background: #f9f0ff;
  color: #9254de;
}

.link-delete {
  color: #ff4d4f;
}

.link-delete:hover {
  background: #fff2f0;
  color: #ff7875;
}

/* 分页区域 */
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 4px;
  align-items: center;
}

.btn-pagination {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-pagination:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.btn-pagination.active {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
}

.btn-pagination:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.btn-pagination.disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: default;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.jump-input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
}

.jump-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 6px;
  }
}

@media (max-width: 768px) {
  .supply-purchase-manage {
    padding: 10px;
  }
  
  .search-form {
    grid-template-columns: 1fr;
  }
  
  .pagination-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination-controls {
    justify-content: center;
  }
  
  .action-links {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-link {
    font-size: 11px;
    padding: 1px 2px;
  }
}
</style>
